package com.tools.starter.swagger.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;

/**
 * @author com.tools
 * @version 1.0
 * @Description: SwaggerConfig
 * <com.tools.starter.swagger>
 * @date Created in 2020/8/17 14:00
 **/
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    @Resource
    private SwaggerProperties swaggerProperties;

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
            .apiInfo(apiInfo())
            // 设置哪些接口暴露给Swagger展示
            .select()
            // 扫描所有有注解的api，用这种方式更灵活
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            // 扫描指定包中的swagger注解
            //.apis(RequestHandlerSelectors.basePackage("com.template.project.tool.swagger"))
            // 扫描所有 .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
            // 设置标题
            .title("标题：" + swaggerProperties.getTitle())
            // 描述
            .description("描述：" + swaggerProperties.getDesc())
            // 作者信息
            .contact(new Contact(swaggerProperties.getAuthor(), null, null))
            // 版本
            .version("版本号:" + swaggerProperties.getVersion())
            .build();
    }
}
